package com.bbcare.sso.client;

import java.util.Date;

import org.json.JSONObject;

import com.bbcare.comm.Constants;
import com.bbcare.comm.SpringAppContext;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class AccountService {

    private static AccountService accountService;

    private Date lastSetTime;

    private JedisPool pool;

    private AccountService() {
        pool = SpringAppContext.getBean("jedisPool", JedisPool.class);
    }

    public static AccountService getInstance() {
        if (accountService == null) {
            accountService = new AccountService();
        }
        return accountService;
    }

    public void setSessionTimeout(String sessionId) {
        Date currTime = new Date();
        if (lastSetTime == null || currTime.getTime() - lastSetTime.getTime() > 10000) {
            lastSetTime = currTime;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.select(2);
                jedis.expire(sessionId, Constants.ACCOUNT_LOGIN_SESSION_TIMEOUT);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
        }
    }

    public Account getAccount(String sessionId) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.select(2);
            String str = jedis.get(sessionId);
            if (str != null) {
                jedis.expire(sessionId, Constants.ACCOUNT_LOGIN_SESSION_TIMEOUT);
                JSONObject json = new JSONObject(str);
                return new Account(json);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
